//
//  OAuthViewController.swift
//  weibo
//
//  Created by 吴婷婷 on 15/11/7.
//  Copyright © 2015年 wutingting. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    lazy var webView = UIWebView()
    
    // MARK: - 监听方法
    @objc private func close (){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    //自动填充用户名密码
    @objc private func autoFill() {
        let js = "document.getElementById('userId').value = '305065393@qq.com';" +
        "document.getElementById('passwd').value = 'qqq123';"
        
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    //MARK: - 设置界面
    override func loadView() {
        view = webView
        
        webView.delegate = self
        
        title = "登陆新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
//        view.backgroundColor = UIColor.whiteColor()
        
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

//MARK: - UIWebViewDelegate
extension OAuthViewController : UIWebViewDelegate {
    ///将要加载请求的代理方法
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL where url.host == "www.baidu.com" else {
            
//            print("继续加载\(request)")
            return true
        }
        
        guard let query = url.query where query.hasPrefix("code=") else {
//            print("取消授权")
            close()
            return false
        }
        
        let code = query.substringFromIndex("code=".endIndex)
        
//        print(query)
//        print("授权码是 " + code)
        
        //4加载 accessToken & 用户信息
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSucceed) -> () in
            if !isSucceed {
                SVProgressHUD.showInfoWithStatus("登录失败")
                delay(0.5){ self.close()  }
            }
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "welcome")
            })
            
        }
        
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }


}
